/* Copyright  2009
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/**
 * @filename: check_stack_overrun.cc
 */
#include <server_includes.h>
#include <session.h>
#include <check_stack_overrun.h>
#include <definitions.h>

#include <error.h>

/*****************************************************************************
	Check stack size; Send error if there isn't enough stack to continue     *
*****************************************************************************/
#if STACK_DIRECTION < 0
#define used_stack(A,B) (long) (A - B)
#else
#define used_stack(A,B) (long) (B - A)
#endif

/*
* db_thread_stack_size is declared in the main.cc.
* db_thread_stack_size = 64K.
*/
extern size_t db_thread_stack_size;

bool check_stack_overrun(Session *session, long margin, void *)
{
  long stack_used;
  assert(session == current_session);

  if ((stack_used=used_stack(session->thread_stack,(char*) &stack_used))
                               >=(long) (db_thread_stack_size - margin))
  { // global.h errbuff[NRERRBUFFS][ERRMSGSIZE]
    sprintf(errbuff[0],ER(ER_STACK_OVERRUN_NEED_MORE),
            stack_used,db_thread_stack_size,margin);
    db_message(ER_STACK_OVERRUN_NEED_MORE,errbuff[0],MYF(ME_FATALERROR));
    return true;
  }
  return false;
}
